package com.itheima.ai.repository;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Properties;


@Slf4j
@Component
@RequiredArgsConstructor
public class LocalPDFFileRepository implements FileRepository{

        //进行VectorStore的持久化
        private final VectorStore vectorStore;
        //存储ChatID和文件路径的映射关系
        private final Properties chatFiles = new Properties();

        @Override
        public boolean save(String chatId, Resource resource) {
            //存储文件到本地目录
            String filename = resource.getFilename();
            //存储到类相对路径中
            File file = new File(Objects.requireNonNull(filename));
            try {
                Files.copy(resource.getInputStream(),file.toPath());
            } catch (IOException e) {
                log.error("保存文件失败",e);
                return false;
            }
            chatFiles.put(chatId,filename);
            return true;
        }

        @Override
        public Resource getFile(String chatId) {
            return new FileSystemResource(chatFiles.getProperty(chatId));
        }

        /**
         * 在项目启动的时候初始化，读取配置文件加载ID和文件的映射关系和向量数据库
         */
        @PostConstruct
        public void init(){
            FileSystemResource fileSystemResource = new FileSystemResource("chat-pdf.properties");
            if (fileSystemResource.exists()) {
                try {
                    chatFiles.load(new BufferedReader(new InputStreamReader(fileSystemResource.getInputStream(), StandardCharsets.UTF_8)));
                } catch (IOException e) {
                    log.error("加载文件失败",e);
                }
            }

            FileSystemResource vectorStoreFile = new FileSystemResource("chat-pdf.json");
            if (vectorStoreFile.exists()) {
                SimpleVectorStore simpleVectorStore = (SimpleVectorStore) vectorStore;
                simpleVectorStore.load(vectorStoreFile);
            }
        }
        @PreDestroy
        public void persistent(){
            try {
                chatFiles.store(new FileWriter("chat-pdf.properties"), LocalDateTime.now().toString());
                SimpleVectorStore simpleVectorStore = (SimpleVectorStore) vectorStore;
                simpleVectorStore.save(new File("chat-pdf.json"));

            }catch (IOException e){
                log.error("持久化文件失败",e);
            }
        }
}
